<template>
  <PageWrapper>
    <BasicTable @register="registerTable">
      <template #form-channelCode="{ model, field }">
        <a-tree-select
          v-model:value="model[field]"
          :tree-data="channelTreeData"
          @change="treeSelectChange(model[field])"
          multiple
          allowClear
          :field-names="{
            label: 'channelName',
            value: 'channelCode',
            children: 'children'
          }"
          treeNodeFilterProp="channelName"
          placeholder="请选择渠道名称"
          :maxTagCount="3"
          showCheckedStrategy="SHOW_ALL"
        ></a-tree-select>
      </template>
      <template #tableTitle>
        <a-space :size="12">
          <a-button v-auth="permissionCodeMap.orderAdd" type="primary" @click="operateUser(operateActionType.ADD)"
            >新增订单</a-button
          >
          <a-button type="primary" v-auth="permissionCodeMap.orderExport" @click="orderExport" :loading="exportLoading"
            >导出</a-button
          >
          <a-button type="primary" v-auth="permissionCodeMap.exportStatement" @click="exportOpen">生成对账单</a-button>
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <!-- <template v-if="column.dataIndex === 'payType'">
          <span v-if="record.payType == 1">首次开通</span>
          <span v-else-if="record.payType == 2">续费</span>
        </template> -->
        <template v-if="column.dataIndex === 'payMethod'">
          <span v-if="record.payMethod == 1">线上支付</span>
          <span v-else-if="record.payMethod == 2">线下支付</span>
          <span v-else-if="record.payMethod == 3">试用</span>
        </template>
        <template v-else-if="column.dataIndex === 'orderStatus'">
          <span class="global-wait-status" v-if="record.orderStatus == 1">待付款</span>
          <span class="global-active-status" v-else-if="record.orderStatus == 2">已完成</span>
          <span class="global-stop-status" v-else-if="record.orderStatus == 3">已关闭</span>
          <span class="global-error-status" v-else-if="record.orderStatus == 4">已失效</span>
        </template>
        <template v-else-if="column.dataIndex === 'tryFlag'">
          <div class="try-out order-status" v-if="record.tryFlag == 1">试用版</div>
          <div class="official order-status" v-else-if="record.tryFlag == 2">正式版</div>
          <div class="return-order order-status" v-else-if="record.tryFlag == 3">退单</div>
        </template>
        <template v-else-if="column.dataIndex === 'invoiceStatus'">
          <template v-if="record.payMethod == 1 && record.orderStatus == 2">
            <span class="global-stop-status" v-if="record.invoiceStatus == 0">待开票</span>
            <span class="global-wait-status" v-else-if="record.invoiceStatus == 1">开票中</span>
            <span class="global-active-status" v-else-if="record.invoiceStatus == 2">开票成功</span>
            <span class="global-error-status" v-else-if="record.invoiceStatus == 3">开票失败</span>
          </template>
          <span v-else>--</span>
        </template>
        <template v-else-if="column.dataIndex === 'orderAmt'">
          <span>{{ formatMoney(record.orderAmt) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button v-auth="permissionCodeMap.orderView" type="link" class="g-operate-btn" @click="viewData(record)"
            >查看</a-button
          >
          <a-button
            type="link"
            v-if="record.tryFlag == 1 && record.showFlag == 1"
            v-auth="permissionCodeMap.genFormalOrder"
            class="g-operate-btn"
            @click="genFormalOrder(operateActionType.ADD, record)"
            >生成正式订单</a-button
          >
          <a-button
            type="link"
            v-if="record.orderStatus == 1 && record.payMethod == 2"
            v-auth="permissionCodeMap.orderEdit"
            class="g-operate-btn"
            @click="operateUser(operateActionType.EDIT, record)"
            >编辑</a-button
          >
        </template>
      </template>
    </BasicTable>
    <OrderAdd @register="orderAddRegister" @operateSuccess="operateSuccess" />
    <OrderView @register="orderViewRegister" @operateSuccess="operateSuccess" />
    <ExportStatement @register="exportStatementRegister" @operateSuccess="operateSuccess"></ExportStatement>
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, createVNode, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getOrderBasicColumns, getSearchFormConfig } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import ExportStatement from './components/ExportStatement.vue'
import OrderAdd from './components/OrderAdd.vue'
import OrderView from './components/OrderView.vue'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { OrderRecord } from '@/types/goods'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import { createChannelTree, transformToTree } from '@/utils'
import { downExcel } from '@/utils/axios/request'
import { formatMoney } from '@/utils/index'
import api from '@/api'
const { orderQueryPage, queryChannelList } = api

const [registerTable, { reload, setPagination, getForm }] = useTable({
  api: orderQueryPage,
  columns: getOrderBasicColumns(),
  useSearchForm: true,
  beforeFetch: beforeParamsFetch,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  indexColumnProps: {
    fixed: 'left'
  },
  rowKey: 'orderNo',
  scroll: { y: constantMap.tableYHeight, x: constantMap.tableXWidth }
})
const [exportStatementRegister, { openModal: exportStatementOpen }] = useModal()
const exportLoading = ref(false)
const channelTreeData = ref<any>([])
const seclectedChannel = ref<any>([])
onMounted(async () => {
  const res = await queryChannelList()
  channelTreeData.value = transformToTree(res.result)
  console.log(res.result, channelTreeData.value)
})
const treeSelectChange = (data: any) => {
  console.log('测试数据======>', data)
  seclectedChannel.value = data
}
function beforeParamsFetch(params: any) {
  const { channelCode, ...rest } = params
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const formChannel = formData.channelCode
  let channelCodeSet
  if (seclectedChannel.value.length > 0 && formChannel) {
    channelCodeSet = seclectedChannel.value
  }
  let paramsData = {
    ...rest,
    channelCodeSet
  }
  return paramsData
}

const [orderAddRegister, { openDrawer: OrderAddOpenDrawer, setDrawerProps }] = useDrawer()
const [orderViewRegister, { openDrawer: OrderViewOpenDrawer }] = useDrawer()

const operateSuccess = () => {
  setPagination({
    current: 1
  })
  reload()
}
const viewData = (record: OrderRecord) => {
  OrderViewOpenDrawer(true, {
    orderNo: record.orderNo,
    packageName: record.packageName,
    tryFlag: record.tryFlag
  })
}

// 订单导出
const orderExport = async () => {
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const { channelCode, ...rest } = formData
  exportLoading.value = true
  let channelCodeSet
  if (channelCode) {
    channelCodeSet = seclectedChannel.value
  }
  try {
    let res = await downExcel(
      '/api/tenant/manager/order/exportExcel',
      {
        ...rest,
        channelCodeSet
      },
      '订单数据'
    )
    exportLoading.value = false
    message.success('导出成功')
  } catch (error) {
    exportLoading.value = false
  }
}
// 导出对账单
const exportOpen = () => {
  exportStatementOpen(true, {
    channelTreeData: channelTreeData.value
  })
}
const operateUser = (type: OperateType, record?: OrderRecord) => {
  setDrawerProps({
    title: operateTxtType[type] + '订单'
  })
  OrderAddOpenDrawer(true, {
    type,
    record
  })
}
const genFormalOrder = (type: OperateType, record?: OrderRecord) => {
  setDrawerProps({
    title: operateTxtType[type] + '订单'
  })
  OrderAddOpenDrawer(true, {
    type,
    record,
    tryToFormal: true
  })
}
</script>

<style lang="less" scoped>
:deep(.ant-table-wrapper) {
  overflow-x: hidden;
}
.order-status {
  text-align: center;
  width: 52px;
  height: 22px;
  line-height: 22px;
  border-radius: 2px;
  font-size: 12px;
  font-weight: 500;
}
.try-out {
  background: #fef7e8;
  border: 1px solid #f7d086;
  color: #d7802e;
}
.official {
  background: #ebfeec;
  border: 1px solid #9defaa;
  color: #4aa353;
}
.return-order {
  color: #c72a2a;
  background: #fbe7e6;
  border: 1px solid #f2a7a5;
}
</style>
